/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.api.runtime.process.operator;

import com.google.common.base.Strings;
import com.je.bpm.api.runtime.process.operator.desc.ProcessGetNextElementParamDesc;
import com.je.bpm.api.runtime.process.operator.validator.ProcessGetNextElementPayloadValidator;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.event.EndEvent;
import com.je.bpm.core.model.gateway.InclusiveGateway;
import com.je.bpm.core.model.task.*;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.engine.RuntimeService;
import com.je.bpm.engine.TaskService;
import com.je.bpm.engine.task.GetTakeNodeNameUtil;
import com.je.bpm.model.process.model.ProcessNextNodeInfo;
import com.je.bpm.model.process.model.impl.ProcessNextNodeInfoImpl;
import com.je.bpm.model.process.results.ProcessNextElementResult;
import com.je.bpm.runtime.process.operator.ProcessGetNextElementOperator;
import com.je.bpm.runtime.process.payloads.ProcessGetNextElementPayload;
import com.je.bpm.runtime.shared.operator.AbstractOperator;
import com.je.bpm.runtime.shared.operator.desc.OperationParamDesc;
import com.je.bpm.runtime.shared.operator.validator.OperatorPayloadParamsValidator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取提交节点信息
 */
public class ProcessGetNextElementOperatorImpl extends AbstractOperator<ProcessGetNextElementPayload, ProcessNextElementResult>
        implements ProcessGetNextElementOperator {

    private OperatorPayloadParamsValidator<ProcessGetNextElementPayload> validator;
    private RepositoryService repositoryService;
    private RuntimeService runtimeService;
    private TaskService taskService;

    public ProcessGetNextElementOperatorImpl(RepositoryService repositoryService, RuntimeService runtimeService, TaskService taskService) {
        this.validator = new ProcessGetNextElementPayloadValidator();
        this.repositoryService = repositoryService;
        this.runtimeService = runtimeService;
        this.taskService = taskService;
    }

    @Override
    public String getId() {
        return OperatorEnum.PROCESS_GET_NEXT_ELEMENT_OPERATOR.getId();
    }

    @Override
    public String getName() {
        return OperatorEnum.PROCESS_GET_NEXT_ELEMENT_OPERATOR.getName();
    }

    @Override
    public OperationParamDesc getParamDesc() {
        return new ProcessGetNextElementParamDesc();
    }

    @Override
    public OperatorPayloadParamsValidator<ProcessGetNextElementPayload> getValidator() {
        return validator;
    }

    @Override
    public ProcessGetNextElementPayload paramsParse(Map<String, Object> params) {
        String taskId = (String) params.get("taskId");
        String pdid = (String) params.get("pdid");
        String prod = (String) params.get(AbstractOperator.PROD);
        Map<String, Object> bean = formatMap(params.get(AbstractOperator.BEAN));
        ProcessGetNextElementPayload processGetNextElementPayload = new ProcessGetNextElementPayload();
        processGetNextElementPayload.setBean(bean);
        processGetNextElementPayload.setTaskId(taskId);
        processGetNextElementPayload.setPdid(pdid);
        processGetNextElementPayload.setProd(prod);
        return processGetNextElementPayload;
    }

    @Override
    public ProcessNextElementResult execute(ProcessGetNextElementPayload processGetNextElementPayload) {
        List<ProcessNextNodeInfo> processNextNodeInfos = new ArrayList<>();
        String taskId = processGetNextElementPayload.getTaskId();
        //获取可以提交的节点信息
        List<Map<SequenceFlow,Boolean>> sequenceFlowList = runtimeService.getSubmitElement(processGetNextElementPayload.getPdid(), taskId, processGetNextElementPayload.getBean(),
                processGetNextElementPayload.getProd());
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processGetNextElementPayload.getPdid());
        for (Map<SequenceFlow, Boolean> sequenceFlowBooleanMap : sequenceFlowList) {
            for (Map.Entry<SequenceFlow, Boolean> sequenceFlowBooleanEntry : sequenceFlowBooleanMap.entrySet()) {
                SequenceFlow sequenceFlow = sequenceFlowBooleanEntry.getKey();
                Boolean aBoolean = sequenceFlowBooleanEntry.getValue();
                //设置节点信息
                ProcessNextNodeInfo processNextNodeInfo = new ProcessNextNodeInfoImpl();
                FlowElement flowElement = bpmnModel.getMainProcess().getFlowElementMap().get(sequenceFlow.getTargetRef());
                if (Strings.isNullOrEmpty(flowElement.getName())) {
                    String takeNodeName = GetTakeNodeNameUtil.builder().getTakeNodeName(flowElement);
                    processNextNodeInfo.setNodeName(takeNodeName);
                } else {
                    processNextNodeInfo.setNodeName(flowElement.getName());
                }

                processNextNodeInfo.setNodeId(sequenceFlow.getTargetRef());
                processNextNodeInfo.setTarget(sequenceFlow.getId());
                processNextNodeInfo.setSubmitDirectly(false);
                if (flowElement instanceof KaiteBaseUserTask) {
                    KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;
                    processNextNodeInfo.setType(kaiteBaseUserTask.getType());
                }
                if (flowElement instanceof EndEvent) {
                    processNextNodeInfo.setType(KaiteTaskCategoryEnum.JSON_END.getType());
                    processNextNodeInfo.setSubmitDirectly(true);
                } else if (flowElement instanceof InclusiveGateway) {
                    if (flowElement.getId().startsWith("aggregation")) {
                        processNextNodeInfo.setSubmitDirectly(true);
                    } else {
                        List<SequenceFlow> list = ((InclusiveGateway) flowElement).getOutgoingFlows();
                        if (list.size() == 1) {
                            if (list.get(0).getTargetFlowElement() instanceof InclusiveGateway) {
                                processNextNodeInfo.setSubmitDirectly(true);
                            }
                        }
                    }
                } else {
                    processNextNodeInfo.setSubmitDirectly(runtimeService.getSubmitDirectly(processGetNextElementPayload.getPdid(), taskId));
                }
                processNextNodeInfo.setIsJump(aBoolean);
                processNextNodeInfos.add(processNextNodeInfo);
            }
        }
        return new ProcessNextElementResult(processGetNextElementPayload, processNextNodeInfos);
    }

}

